import { Component, OnInit, OnDestroy, AfterViewInit } from "@angular/core";
import { Select, Store } from "@ngxs/store";
import { Observable, interval } from "rxjs";
import { Breadcrumb, AppActions } from "src/app/app-store";
import {
  NzNotificationService,
  NzModalService,
  NzMessageService,
} from "ng-zorro-antd";
import { sample } from "rxjs/operators";
import { Router } from "@angular/router";
import { KVAny } from "src/app/shared/type/kv";
import { environment } from "src/environments/environment";

export interface MenuRoute {
  name: string;
  url: string;
  icon?: string;
  param?: KVAny;
  children?: MenuRoute[];
}

export interface MenuTable {
  menu: MenuRoute[];
  name: string;
  id: number;
  code: string;
  url?: string;
  icon?: string;
  param?: KVAny;
  children?: MenuTable[];
}

@Component({
  selector: "n-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"],
})
export class HomeComponent implements OnInit, OnDestroy, AfterViewInit {
  environment = environment;
  tabIndex = 0;
  menuRouteName: string;
  menuRouteUrl: string;
  urlState: number;
  urlList = [
    {
      value: "./auth",
      iframeId: "auth",
      id: null
    },
    {
      value: "./survey",
      iframeId: "survey",
      id: null
    },
    {
      value: "./circle",
      iframeId: "circle",
      id: null
    },
    {
      value: "./log",
      iframeId: "log",
      id: null
    },
    {
      value: "./compass",
      iframeId: "compass",
      id: null
    },
    {
      value: "./statistic",
      iframeId: "statistic",
      id: null
    },
    {
      value: "./portrait",
      iframeId: "portrait",
      id: null
    }
  ];
  iframeUrl: string;
  doctorCircleRoutes: MenuRoute[];
  settingRoutes: MenuRoute[];
  isCollapsed = false;
  isUp = false;
  spinning = true;

  // authorityRoutes: MenuRoute[];
  // settingRoutes: MenuRoute[];
  routeSet: MenuRoute[];
  menuTable: MenuTable[] = [];
  @Select((state) => state.app.breadcrumb) breadcrumb$: Observable<
    Breadcrumb[]
  >;

  @Select((state) => state.app.sessionStatus) sessionStatus$: Observable<
    boolean
  >;

  @Select((state) => state.app.serviceStatus) serviceStatus$: Observable<
    string
  >;

  constructor(
    private notification: NzNotificationService,
    private router: Router,
    private modalService: NzModalService,
    private msg: NzMessageService
  ) {}

  ngAfterViewInit(): void {
    this.sessionStatus$.pipe(sample(interval(10000))).subscribe((status) => {
      if (status) {
        this.notification.create(
          "error",
          "会话失效",
          "由于您长时间未操作或在别处登录，您当前的登录状态已丢失，请重新登录！",
          { nzDuration: 10000 }
        );
      }
    });

    this.serviceStatus$.pipe(sample(interval(500))).subscribe((status) => {
      if (status) {
        this.notification.create("error", "服务调用失败", status, {
          nzDuration: 2000,
        });
      }
    });

    // 刷新页面获取是否有点击菜单
    if (sessionStorage.getItem("menuRouteUrl")) {
      this.menuRouteName = sessionStorage.getItem("menuRouteName");
      this.menuRouteUrl = sessionStorage.getItem("menuRouteUrl");
      this.iframeUrl = sessionStorage.getItem("menuRouteUrl");
      this.tabIndex = +sessionStorage.getItem("tabIndex");
      this.routeSet = this.menuTable[this.tabIndex].menu;
      this.setIfranmeUrl(this.iframeUrl);
    } else {
      // 无则关闭加载显示欢迎页
      this.urlState = null;
      this.closeLoading();
    }
  }

  ngOnInit() {
    const menu = JSON.parse(sessionStorage.getItem("menu"));
    if (menu) {
      this.menuTable = menu.modules;
      if (this.menuTable.length > 0) {
        this.routeSet = this.menuTable[this.tabIndex].menu;
      }
    } else {
      this.router.navigate(["/login"]);
    }
  }

  ngOnDestroy() {}

  // 点击菜单
  updateBreadcrumb(route: MenuRoute, menuRoute: MenuRoute) {
    this.menuRouteName = menuRoute.name;
    this.menuRouteUrl = route.url;
    sessionStorage.setItem("menuRouteName", this.menuRouteName);
    sessionStorage.setItem("menuRouteUrl", this.menuRouteUrl);
    sessionStorage.setItem("tabIndex", this.tabIndex.toString());
    this.iframeUrl = route.url;
    this.setIfranmeUrl(this.iframeUrl);
    // this.closeLoading();
  }

  // 关闭load
  closeLoading() {
    this.spinning = false;
  }

  // 切换系统
  change(key: number, id: number) {
    // 如果id为99 则为老后台 待app老后台删除后， 这段可删除
    if (id === 99) {
      window.open("https://static.yishifuwu.cn/old/#!/home");
      return;
    }
    // delete end

    const menu = JSON.parse(sessionStorage.getItem("menu"));
    this.routeSet = menu.modules[key].menu;
    this.tabIndex = key;
  }

  logout() {
    this.isUp = false;
    this.modalService.confirm({
      nzTitle: "退出登录",
      nzContent: "是否退出登录？",
      nzOnOk: () => {
        sessionStorage.clear();
        window.location.href = "/";
      },
    });
  }

  changePassWord() {
    // 修改密码跳转
    this.isUp = false;
    this.iframeUrl = "./auth/#/authority/password";
    sessionStorage.setItem("menuRouteName", "修改密码");
    sessionStorage.setItem("menuRouteUrl", this.iframeUrl);
    this.setIfranmeUrl(this.iframeUrl);
  }

  setIfranmeUrl(url: string) {
    this.spinning = true;
    // 判断url是为空
    if (url === "") {
      this.urlState = null;
      this.closeLoading();
      return;
    }

    // 通过url判断是否存在预加载项目中
    const urlKye = this.getUrlKey(url);
    this.urlState = urlKye;

    // 如果urlKye 不等于-1 则在预加载项目中
    if (urlKye !== -1) {
      const urlList = this.urlList[urlKye];

      // 关闭其他菜单
      // tslint:disable-next-line: prefer-for-of
      for (let i = 0; i < this.urlList.length; i++) {
        if (this.urlList[i].id) {
          document.getElementById(this.urlList[i].id).style.display = "none";
        }
      }
      // 如果id 不为null 则已建好iframe 修改src即可
      if (urlList.id) {
        const iframe = document.getElementById(urlList.id);
        iframe.setAttribute("src", url);
        iframe.style.display = "block";
        this.closeLoading();
      } else {
        // 如果id为null 则需新建iframe 插入 iframe-box 到这里即可
        this.urlList[urlKye].id = urlList.iframeId;
        const iframeBox = document.createElement("iframe");
        iframeBox.setAttribute("src", url);
        iframeBox.setAttribute("id", urlList.iframeId);
        iframeBox.onload = () => {
          this.closeLoading();
        };
        document.getElementById("iframe-box").appendChild(iframeBox);
      }
    } else {
      // 如果urlKye为 -1 则是未知菜单  临时创建iframe 即用即删
      const iframeBox1 = document.getElementById("iframe-box1");
      iframeBox1.innerHTML = "";
      const iframe = document.createElement("iframe");
      iframe.setAttribute("src", url);
      iframe.setAttribute("id", "iframe-childer");
      iframe.setAttribute("name", "iframe-childer");
      iframe.onload = () => {
        this.closeLoading();
      };
      iframeBox1.appendChild(iframe);
    }
  }

  // 获取下标
  getUrlKey(url: string) {
    for (let i = 0; i < this.urlList.length; i++) {
      if (url.indexOf(this.urlList[i].value) !== -1) {
        return i;
      }
    }
    return -1;
  }
}
